package com.tywj.buscustomerapp.view.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.MyTicketBean;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.ScreenUtils;
import com.tywj.buscustomerapp.utils.TimeRender;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.activity.MapTicketActivity;
import com.tywj.buscustomerapp.view.activity.MyTicketActivity;
import com.tywj.buscustomerapp.view.myview.LoadingDialog;
import com.tywj.buscustomerapp.view.myview.ToastJoe;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Time;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ViewPagerViewAdapter extends PagerAdapter implements View.OnTouchListener {
    private Context mContext;
    private List<MyTicketBean> mList = new ArrayList<>();
    private Timer timer=null;
    private MyTicketActivity activity;


    public ViewPagerViewAdapter(Context mContext, List<MyTicketBean> mList,Activity activity) {
        this.mContext = mContext;
        this.mList = mList;
        this.activity = (MyTicketActivity) activity;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    private Queue<View> viewPool = new LinkedList<>(); //View池

    @Override public Object instantiateItem(ViewGroup container, final int position) {
        View view;
        final ViewHolder viewHolder;
        //当池子中有存货就复用，否则才inflate
        if(viewPool.size() > 0){
            view = viewPool.poll();
            viewHolder = (ViewHolder) view.getTag();
        }else{
            view = LayoutInflater.from(mContext).inflate(R.layout.ticket_layout, container, false);
            viewHolder = new ViewHolder();
            viewHolder.textView = view.findViewById(R.id.ticket_date);
            viewHolder.imageView = view.findViewById(R.id.ticket_touch);
            viewHolder.name = view.findViewById(R.id.ticket_name);
            viewHolder.start = view.findViewById(R.id.start);
            viewHolder.startTIme = view.findViewById(R.id.start_time);
            viewHolder.end = view.findViewById(R.id.end);
            viewHolder.endTime = view.findViewById(R.id.end_time);
            viewHolder.number = view.findViewById(R.id.bus_number);
            viewHolder.checked = view.findViewById(R.id.checked);
            viewHolder.ticketid = view.findViewById(R.id.ticket_id);
            viewHolder.progressBar = view.findViewById(R.id.number_progress_bar);
//            viewHolder.parView = view.findViewById(R.id.number_progress_bar_1);
            viewHolder.isMonthTicket = view.findViewById(R.id.ismonth);
            viewHolder.findBus = view.findViewById(R.id.bus_location);
//            viewHolder.more = view.findViewById(R.id.ticket_more);
            viewHolder.findBus.setVisibility(View.GONE);
            viewHolder.errorMessage = view.findViewById(R.id.error_info);
            view.setTag(viewHolder);

        }

        if (!mList.get(position).isMonth) {
            viewHolder.isMonthTicket.setText("单次票");
            viewHolder.textView.setText(mList.get(position).getBusTime());
            if (mList.get(position).getTravelName()!=null && !mList.get(position).getTravelName().equals("")){
                viewHolder.name.setText(mList.get(position).getTravelName());
                viewHolder.ticketid.setText(mList.get(position).getId());
            }else {
                viewHolder.name.setText(mList.get(position).getMyStart() + "-" + mList.get(position).getMyEnd());
            }
            viewHolder.imageView.setTag(R.id.image_view, mList.get(position));
            viewHolder.imageView.setTag(R.id.bar, viewHolder.progressBar);
            viewHolder.imageView.setTag(R.id.bus_number, viewHolder.number);
            viewHolder.imageView.setOnTouchListener(this);
            if (mList.get(position).getMyStartTime()!=null && mList.get(position).getMyStartTime().length()>2 && Integer.valueOf(mList.get(position).getMyStartTime().substring(0,2))>12){
                viewHolder.errorMessage.setVisibility(View.GONE);
            }else{
                viewHolder.errorMessage.setVisibility(View.VISIBLE);
            }
            Log.i("VIEWPAGER",mList.get(position).getMyStartTime());
            if (mList.get(position).getState().equals("已乘车")) {
                viewHolder.imageView.setPadding(0, 0, 0, 0);
                Glide.with(view.getContext()).load(R.drawable.success).into(viewHolder.imageView);
                viewHolder.checked.setText("验票成功！");
                viewHolder.number.setTextSize(30);
                viewHolder.number.setTextColor(view.getResources().getColor(R.color.appColor));
            } else if (mList.get(position).getState().equals("待乘车")) {
                viewHolder.imageView.setPadding(30, 30, 30, 30);
                Glide.with(view.getContext()).load(R.mipmap.fingerprint).into(viewHolder.imageView);
                viewHolder.checked.setText("发车当日才可验票~");
            }
            if (mList.get(position).getState().equals("待乘车")||mList.get(position).getState().equals("已乘车")){
                viewHolder.findBus.setVisibility(View.VISIBLE);
                viewHolder.findBus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(v.getContext(), MapTicketActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("ticket", mList.get(position));
                        intent.putExtras(bundle);
                        v.getContext().startActivity(intent);
                    }
                });
            }
        }else{
            viewHolder.isMonthTicket.setText("月票");
            viewHolder.textView.setText(mList.get(position).getYear()+"年"+mList.get(position).getMonth()+"月");
            if (mList.get(position).getTravelName()!=null && !mList.get(position).getTravelName().equals("")){
                viewHolder.name.setText(mList.get(position).getTravelName());
            }else {
                viewHolder.name.setText(mList.get(position).getMyStart() + "-" + mList.get(position).getMyEnd());
            }
            viewHolder.imageView.setPadding(0,0,0,0);
            Glide.with(viewHolder.imageView.getContext()).load(R.drawable.success).into(viewHolder.imageView);
            viewHolder.checked.setText("展示车票上车");

        }


//        viewHolder.progressBar.setVisibility(View.GONE);
//        viewHolder.parView.setVisibility(View.VISIBLE);
        viewHolder.startTIme.setText(mList.get(position).getMyStartTime());
        viewHolder.endTime.setText(mList.get(position).getMyEndTime());
        viewHolder.start.setText(mList.get(position).getMyStart());
        viewHolder.end.setText(mList.get(position).getMyEnd());
        viewHolder.number.setText(mList.get(position).getBusNumber());
//        viewHolder.more.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mList.get(position).isMonth){
//
//                }else{
//
//                }
//                showPop(v.getContext(),viewHolder.imageView);
//            }
//        });
        container.addView(view);
        return view;
    }

    @Override public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        //将当前View加入到池子中
        viewPool.offer((View) object);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    private float ax=0;
    private float ay=0;
    @Override
    public boolean onTouch(final View v, final MotionEvent event) {
        MyTicketBean ticketBean = (MyTicketBean) v.getTag(R.id.image_view);
        String thisDay = TimeRender.getFullDateStr1();
        final NumberProgressBar bar = (NumberProgressBar) v.getTag(R.id.bar);
        if (thisDay.equals(ticketBean.getBusTime()) && ticketBean.getState().equals("待乘车")){//TimeRender.compareTime6(ticketBean.getMyStartTime())
            switch (event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    ((ImageView) v).setImageResource(R.mipmap.fingerprint_orange);
                    if (bar!=null){
                        bar.setVisibility(View.VISIBLE);
                        bar.setProgress(0);
                    }
                    ax = event.getX();
                    ay = event.getY();
                    if (timer!=null){
                        timer.cancel();
                    }
                    timer = new Timer();
                    final TimerTask task=new TimerTask() {
                        @Override
                        public void run() {
                            ((Activity) bar.getContext()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (bar.getProgress()==100){
                                        timer.cancel();
                                        Log.i("taylor","this"+bar.getProgress());
                                        doG0Bus(v,true);
//                                        bar.setVisibility(View.GONE);
                                    }else if (bar.getProgress()<100){
                                        bar.setProgress(bar.getProgress() + 1);
                                    }
                                }
                            });

                        }
                    };
                    timer.schedule(task,0,10);
                    break;
                case MotionEvent.ACTION_UP:
                    if (bar!=null){
                        bar.setProgress(0);
//                        bar.setVisibility(View.GONE);
                    }
                    if (timer!=null){
                        timer.cancel();
                    }
                    ((ImageView) v).setImageResource(R.mipmap.fingerprint);
                    break;
                case MotionEvent.ACTION_MOVE:
                    if ((Math.abs((event.getX() - ax)) > 10) || (Math.abs(event.getY() - ay) > 10)) {
                        if (bar!=null){
                            bar.setProgress(0);
//                            bar.setVisibility(View.GONE);
                        }
                        if (timer!=null){
                            timer.cancel();
                        }
                        ((ImageView) v).setImageResource(R.mipmap.fingerprint);
                    }
                    break;
            }
        }else{
            if (!ticketBean.isMonth && ticketBean.getState().equals("待乘车")) {
                ToastJoe.getmToastJoe().ToastLongShow(v.getContext(), null, "发车当日才可验票");
            }else if (!ticketBean.isMonth &&ticketBean.getState().equals("已乘车")){
                ToastJoe.getmToastJoe().ToastLongShow(v.getContext(), null, "您已验票");
            }
        }
        return true;
    }

    /**
     * 乘车
     * @param view
     * @param event
     */
    private void doG0Bus(final View view, boolean event){
        if (event) {
            ((ImageView) view).setImageResource(R.mipmap.fingerprint);
            final LoadingDialog dialog = new LoadingDialog(view.getContext());
            Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                public void subscribe(ObservableEmitter<String> e) {
                    try {
                        String msg = WebServicrUtils.getInstance().doGoBus(((MyTicketBean) view.getTag(R.id.image_view)).getId());
                        if (msg.equals("ok")) {
                            e.onNext(msg);
                            e.onComplete();
                        } else {
                            e.onError(null);
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
//                        e.onError(null);
                    } catch (XmlPullParserException e1) {
                        e1.printStackTrace();
//                        e.onError(null);
                    } catch (Exception e1) {
                        e1.printStackTrace();
//                        e.onError(null);
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            if (dialog != null && !dialog.isShowing()) {
                                dialog.show();
                            }
                        }

                        @Override
                        public void onNext(String s) {
                            if (view!=null && view.getContext()!=null) {
                                try{
                                    ToastJoe.getmToastJoe().ToastShowRight(view.getContext(), null, "检票成功");
                                    view.setPadding(0, 0, 0, 0);
                                    Glide.with(view.getContext()).load(R.drawable.success).into((ImageView) view);
                                    ((MyTicketBean) view.getTag(R.id.image_view)).setState("已乘车");
                                    ((TextView) (view.getTag(R.id.bus_number))).setTextColor(view.getResources().getColor(R.color.appColor));
                                    ((TextView) (view.getTag(R.id.bus_number))).setTextSize(30);
                                    if (dialog != null && dialog.isShowing()) {
                                        dialog.dismiss();
                                    }
                                }catch (IllegalStateException e){
                                    if (dialog != null && dialog.isShowing()) {
                                        dialog.dismiss();
                                    }
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastJoe.getmToastJoe().ToastShow(view.getContext(), null, "检票失败，请重试");
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }


    private void showPop(Context context, ImageView imageView){
        View contentView = LayoutInflater.from(context).inflate(R.layout.pop_layout, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        darkenBackground(0.5f,activity);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f,activity);
            }
        });
        int[] loacs = new int[2];
        imageView.getLocationOnScreen(loacs);
       int[] x = ScreenUtils.getScreenSize(activity);
        Log.i("taylor",x[0]+":"+(x[1]));
        Log.i("taylor",(x[0]-loacs[0])+":"+(loacs[1]));
//        popupWindow.showAsDropDown(imageView,0,-(x[0]-loacs[0]),Gravity.START);
//        popupWindow.showAtLocation((View) imageView.getParent(),Gravity.START,loacs[1]-500,loacs[0]/2);
    }
    private void darkenBackground(Float bgcolor,Activity activity){
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgcolor;
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        activity.getWindow().setAttributes(lp);
    }

    private static int[] calculatePopWindowPos(final View anchorView, final View contentView) {
        final int windowPos[] = new int[2];
        final int anchorLoc[] = new int[2];
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = contentView.getMeasuredHeight();
        final int screenWidth = contentView.getMeasuredWidth();
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
        } else {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return windowPos;
    }

    //定义一个ViewHolder
    class ViewHolder{
        TextView  textView;
        ImageView imageView;
        TextView name;
        TextView startTIme;
        TextView endTime;
        TextView start;
        TextView end;
        TextView number;
        TextView checked;
        TextView ticketid;
        NumberProgressBar progressBar;
        TextView isMonthTicket;
        TextView findBus;
        View parView;
        TextView errorMessage;
//        ImageView more;
    }

}
